#include "usermgr.h"
#include "util.h"
#include <sstream>
#include "global.h"
#include "minutelisten.h"


UserMgr::UserMgr()
{
    MinuteListen::Instance()->Register(__FUNCTION__, [this](std::int64_t tick){
        if (0 != (tick % 60)) return;
        m_mgr.OnTick();
    });
}
UserMgr::~UserMgr()
{
}

bool UserMgr::Update(stUser&& user)
{
    if (user.username.empty()) 
    {
        return false;
    }
    m_mgr.Set(user.username, std::move(user));
    return true;
}
bool UserMgr::Update(const stUser& user)
{
    if (user.username.empty()) 
    {
        return false;
    }
    m_mgr.Set(user.username, user);
    return true;
}
stUser* UserMgr::Get(const std::string& username)
{
    return m_mgr.ActiveGet(username);
}

stUser* UserMgr::GenUser(const std::string& agency, const std::string& currency, std::int64_t balance, const std::string& username)
{
    static std::int32_t index = 0;
    std::int64_t now = CTools::GetUnixTime();
    stUser user;
    if (username.empty())
    {
        std::stringstream ss;
        ss << "u_" << TGlobal::_svid << "_" << now << "_" << index++;
        user.username = ss.str();
    }
    else
    {
        user.username = username;
    }
    user.agency = agency;
    user.currency = currency;
    user.balance = balance;
    return m_mgr.SetAndGet(user.username, std::move(user));
}











